package com.micromall.admin;

import com.google.common.collect.Maps;
import com.micromall.repository.CertifiedInfoMapper;
import com.micromall.repository.DistributionRelationMapper;
import com.micromall.repository.MemberMapper;
import com.micromall.repository.OrderMapper;
import com.micromall.repository.entity.CashAccount;
import com.micromall.repository.entity.CertifiedInfo;
import com.micromall.repository.entity.Member;
import com.micromall.repository.entity.common.CertifiedStatus;
import com.micromall.service.CashAccountService;
import com.micromall.service.CertifiedInfoService;
import com.micromall.service.OrderService;
import com.micromall.service.ShortMessageService;
import com.micromall.service.TransactionalExecuteService;
import com.micromall.web.resp.ResponseEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhangzx on 16/3/21.
 * 会员管理
 */
@RestController
@RequestMapping(value = "/admin/member")
public class AdminMemberController extends AdminBasicController {

	@Resource
	private DistributionRelationMapper  distributionRelationMapper;
	@Resource
	private MemberMapper                memberMapper;
	@Resource
	private OrderMapper                 orderMapper;
	@Resource
	private CashAccountService          cashAccountService;
	@Resource
	private ShortMessageService         shortMessageService;
	@Resource
	private CertifiedInfoService        certifiedInfoService;
	@Resource
	private CertifiedInfoMapper         certifiedInfoMapper;
	@Resource
	private OrderService                orderService;
	@Resource
	private TransactionalExecuteService transactionalExecuteService;

	// 会员列表
	@RequestMapping(value = "/list")
	public ResponseEntity<?> list(String query, @RequestParam(defaultValue = "1") int pageNo, Integer pageSize) {
		Map params = Maps.newHashMap();
		if (StringUtils.isNotBlank(query)) {
			params.put("query", query);
		}
		return ResponseEntity.SuccessPage(memberMapper.selectAdminPage(params, new RowBounds(pageNo, resizeLimit(pageSize))));
	}

	// 会员账户详情
	@RequestMapping(value = "/details")
	public ResponseEntity<?> details(int id) {
		Member member = memberMapper.selectByPrimaryKey(id);
		CashAccount cashAccount = cashAccountService.getCashAccount(member.getId());
		CertifiedInfo certifiedInfo = certifiedInfoService.getCertifiedInfo(member.getId());
		Map<String, Object> data = new HashMap<>();

		// 基本信息
		data.put("id", member.getId());
		data.put("nickname", member.getNickname());
		data.put("avatar", member.getAvatar());
		data.put("level", member.getLevel());
		data.put("gender", member.getGender());
		data.put("birthday", member.getBirthday());
		data.put("source", "微信");
		data.put("registerTime", member.getRegisterTime());
		data.put("lastLoginTime", member.getLastLoginTime());
		data.put("lastLoginIp", member.getLastLoginIp());

		// 认证信息
		if (certifiedInfo != null) {
			data.put("name", certifiedInfo.getName());
			data.put("phone", certifiedInfo.getPhone());
			data.put("idCarNo", certifiedInfo.getIdCarNo());
			data.put("idCarImage1", certifiedInfo.getIdCarImage1());
			data.put("idCarImage0", certifiedInfo.getIdCarImage0());
			data.put("status", certifiedInfo.getStatus());
			data.put("auditTime", certifiedInfo.getAuditTime());
		}

		// 资金信息
		data.put("balance", cashAccount.getBalance().toPlainString());
		data.put("totalSales", cashAccount.getTotalSales().toPlainString());
		data.put("totalCommission", cashAccount.getTotalCommission().toPlainString());
		data.put("commission", cashAccount.getAvailableCommission().toPlainString());

		// 分销会员
		data.put("lv1", distributionRelationMapper.lowerMemberStat(id, 1));
		data.put("lv2", distributionRelationMapper.lowerMemberStat(id, 2));

		// 下单数量
		data.put("orderCount", orderMapper.statMemberOrderCount(id));

		return ResponseEntity.Success(data);
	}

	/**
	 * 证件信息
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/certifiedInfo")
	public ResponseEntity<?> certifiedInfo(int id) {
		return ResponseEntity.Success(certifiedInfoService.getCertifiedInfo(id));
	}

	/**
	 * 我的订单列表（包含各种状态的订单）[0:待付款、1:待发货、2:待收货、3:已完成、4:退货/取消]
	 *
	 * @return
	 */
	@RequestMapping(value = "/orders")
	public ResponseEntity<?> orders(int id, @RequestParam(defaultValue = "1") int pageNo, Integer pageSize) {
		return ResponseEntity.SuccessPage(orderService.findAdminOrders(id, pageNo, resizeLimit(pageSize)));
	}

	/**
	 * 分销会员列表
	 *
	 * @param status
	 * @param query
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value = "/distribution_list")
	public ResponseEntity<?> distribution_list(Integer status, String query, @RequestParam(defaultValue = "1") int pageNo, Integer pageSize) {
		Map params = Maps.newHashMap();
		if (StringUtils.isNotBlank(query)) {
			params.put("query", query);
		}
		if (status != null) {
			params.put("status", status);
		}

		return ResponseEntity.Success(certifiedInfoMapper.selectAdminPage(params, new RowBounds(pageNo, resizeLimit(pageSize))));
	}

	// 分销会员详情
	@RequestMapping(value = "/distribution_details")
	public ResponseEntity<?> distribution_details(int id) {
		CashAccount cashAccount = cashAccountService.getCashAccount(id);
		CertifiedInfo certifiedInfo = certifiedInfoService.getCertifiedInfo(id);
		Member member = memberMapper.selectByPrimaryKey(id);
		Map<String, Object> data = new HashMap<>();

		// 认证信息
		data.put("name", certifiedInfo.getName());
		data.put("phone", certifiedInfo.getPhone());
		data.put("idCarNo", certifiedInfo.getIdCarNo());
		data.put("idCarImage1", certifiedInfo.getIdCarImage1());
		data.put("idCarImage0", certifiedInfo.getIdCarImage0());
		data.put("status", certifiedInfo.getStatus());
		data.put("auditTime", certifiedInfo.getAuditTime());
		data.put("level", member.getLevel());

		// 资金信息
		data.put("balance", cashAccount.getBalance().toPlainString());
		data.put("totalSales", cashAccount.getTotalSales().toPlainString());
		data.put("totalCommission", cashAccount.getTotalCommission().toPlainString());
		data.put("commission", cashAccount.getAvailableCommission().toPlainString());

		// 分销会员
		data.put("lv1", distributionRelationMapper.lowerMemberStat(id, 1));
		data.put("lv2", distributionRelationMapper.lowerMemberStat(id, 2));

		return ResponseEntity.Success(data);
	}

	/**
	 * 认证审核
	 *
	 * @param id
	 * @param auditlog
	 * @param agreed
	 * @return
	 */
	@RequestMapping(value = "/distribution_audit")
	public ResponseEntity<?> distribution_audit(int id, String auditlog, boolean agreed) {
		CertifiedInfo certifiedInfo = certifiedInfoService.getCertifiedInfo(id);
		/*if (certifiedInfo.getStatus() == CertifiedStatus.审核通过) {
			throw new LogicException("不能重复审核");
		}*/

		certifiedInfo.setAuditlog(auditlog);
		CertifiedInfo _Modify = new CertifiedInfo();
		_Modify.setUid(id);
		_Modify.setAuditTime(new Date());
		transactionalExecuteService.execute(() -> {
			if (agreed) {
				_Modify.setStatus(CertifiedStatus.审核通过);
				_Modify.setAuditlog("通过审核");
				certifiedInfoMapper.updateByPrimaryKey(_Modify);
				shortMessageService.sendCertifiedAuditNotify(certifiedInfo.getPhone(), certifiedInfo.getName(), "通过");
			} else {
				_Modify.setStatus(CertifiedStatus.审核不通过);
				_Modify.setAuditlog(auditlog);
				certifiedInfoMapper.updateByPrimaryKey(_Modify);
				shortMessageService.sendCertifiedAuditNotify(certifiedInfo.getPhone(), certifiedInfo.getName(), "未通过");
			}
		});
		return ResponseEntity.Success();
	}

	@RequestMapping(value = "/change_balance")
	public ResponseEntity<?> change_balance(int id, int amount, String reason) {
		transactionalExecuteService.execute(() -> cashAccountService.changeBalance(id, amount,reason));
		return ResponseEntity.Success();
	}
}
